'use strict';

/**
 * @ngdoc directive
 * @name jgappApp.directive:bdMap
 * @description
 * # bdMap
 */
angular.module('jgappApp')
    .directive('bdMap', function(MapService) {
        return {
            scope: {
                options: '=',
                ak: '@',
                map: '=map',
                offline: '='
            },
            template: '<div ng-style="divStyle"><label ng-style="labelStyle">{{ offlineWords }}</label></div>',
            restrict: 'AE',
            link: function postLink(scope, element, attrs) {
                var defaultOpts = {
                    navCtrl: true,
                    scaleCtrl: true,
                    overviewCtrl: true,
                    enableScrollWheelZoom: true,
                    zoom: 10
                };

                var defaultOfflineOpts = {
                    retryInterval: 30000,
                    txt: 'OFFLINE'
                };
                var opts = angular.extend({}, defaultOpts, scope.options);
                var offlineOpts = angular.extend({}, defaultOfflineOpts, scope.offline);
                scope.offlineWords = offlineOpts.txt;

                var opts = scope.options;
                var map = MapService.createInstance(scope.options, element);
                scope.map = map
                    //create markers
                var previousMarkers = [];
                scope.$watch('options.center', function(newValue, oldValue) {
                    map.centerAndZoom(new BMap.Point(opts.center.longitude,
                        opts.center.latitude), opts.zoom);
                    MapService.redrawMarkers(map, previousMarkers, opts);

                }, true);

                scope.$watch('options.markers', function(newValue, oldValue) {
                    MapService.redrawMarkers(map, previousMarkers, opts);
                }, true);


                // var divStyle = {
                //     width: '100%',
                //     height: '100%',
                //     backgroundColor: '#E6E6E6',
                //     position: 'relative',
                //     opacity: 0
                // };

                // var labelStyle = {
                //     fontSize: '30px',
                //     position: 'absolute',
                //     top: '50%',
                //     marginTop: 0,
                //     left: '50%',
                //     marginLeft: 0
                // };
                // scope.divStyle = divStyle;
                // scope.labelStyle = labelStyle;

                // setTimeout(function() {
                //     var $label = document.querySelector('bd-map div label');
                //     scope.labelStyle.marginTop = $label.clientHeight / -2 + 'px';
                //     scope.labelStyle.marginLeft = $label.clientWidth / -2 + 'px';
                //     scope.$apply();
                // });

            }
        };
    });
